package net.vkits.common.filter;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by ethan-liu on 16/6/17.
 */
@Component
public class JwtFilter extends GenericFilterBean {
    private static final Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        logger.info("HttpServletRequest getServletPath is: {}", request.getServletPath());
        if (request.getServletPath().equals("/api/v2/banners") ||
                request.getServletPath().equals("/api/v2/contents") ||
                request.getServletPath().contains("detail") ||
                request.getServletPath().equals("/api/v2/qas") ) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        final String authHeader = request.getHeader("api_key");
        final String path = request.getServletPath();
        if (!path.contains("smscode") && !path.contains("login")) {
            logger.info("get Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer")) {
                if (request.getServletPath().equals("/api/v2/posts/list")) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid Authorization header.");
                return;
            }
            if (authHeader.length() > 7) {
                final String token = authHeader.substring(7);
                try {
                    final Claims claims = JwtHelper.parseJWT(token);
                    request.setAttribute("claims", claims);
                } catch (ServletException ex) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token.");
                    return ;
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
